<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>文章列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            v-model="selectMsg.msg"
            clearable
            @clear="selectArticleList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handSelect"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogvisible = true"
            >添加文章</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="articlelist" stripe border>
        <el-table-column prop="id" label="id" width="50px"> </el-table-column>
        <el-table-column prop="articleName" label="文章名"></el-table-column>
        <el-table-column prop="articleTitle" label="文章标题">
        </el-table-column>
        <el-table-column prop="articleAbstract" label="文章简介">
        </el-table-column>
        <el-table-column prop="articleTypeId" label="文章类型" width="50px">
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createdTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间">
          <template slot-scope="scope">
            {{ scope.row.updatedTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column prop="adminsId" label="发布者id" width="50px">
        </el-table-column>
        <el-table-column prop="isActived" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isActived"
              @change="ArticleStatechanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEidtDialog(scope.$index, scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="DeleteArticle(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.pager.currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="this.pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.pager.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加文章对话框区域 -->
    <el-dialog
      title="添加文章"
      :visible.sync="addDialogvisible"
      :ishljs="true"
      ref="md"
      @imgAdd="imgAdd"
      @imgDel="imgDel"
      width="50%"
      @close="addDialogclosed"
    >
      <el-form ref="addDialogRef">
        <!-- 内容主体区域 -->
        <el-form :model="addForm" ref="addFormRef" label-width="70px">
          <!-- 类型选择器 -->
          <el-select
            v-model="addForm.articleTypeId"
            clearable
            placeholder="请选择文章类型"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.articleTypeName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <div style="margin: 20px 0"></div>
          <div clearable>
            <el-input
              type="text"
              placeholder="请输入名称"
              v-model="addForm.articleName"
              maxlength="10"
              show-word-limit
            ></el-input>
            <div style="margin: 20px 0"></div>
            <el-input
              type="text"
              placeholder="请输入标题"
              v-model="addForm.articleTitle"
              maxlength="10"
              show-word-limit
            >
            </el-input>
            <div style="margin: 20px 0"></div>
            <el-input
              type="textarea"
              placeholder="请输入简介"
              v-model="addForm.articleAbstract"
              maxlength="30"
              show-word-limit
            >
            </el-input>
            <div style="margin: 20px 0"></div>
            <div id="editor">
              <mavon-editor
                style="height: 100%; width: 100%"
                v-model="addForm.articleContent"
                :ishljs="true"
                ref="md"
                @imgAdd="imgAdd"
                @imgDel="imgDel"
              ></mavon-editor>
            </div>
            <div style="margin: 10px 0"></div>
          </div>
        </el-form>
      </el-form>

      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogvisible = false">取消</el-button>
        <el-button @click="savedraft()" type="info">保存草稿</el-button>
        <el-button type="primary" @click="pushArticle()">发布文章</el-button>
      </span>
    </el-dialog>
    <!-- 编辑文章对话框区域 -->
    <el-dialog
      title="编辑文章"
      :visible.sync="editDialogvisible"
      width="50%"
      @close="editDialogclosed"
    >
      <!-- 内容主体区域 -->
      <span>
        <el-form ref="editDialogRef">
          <!-- 内容主体区域 -->
          <el-form :model="editForm" ref="editFormRef" label-width="70px">
            <!-- 类型选择器 -->
            <el-select
              v-model="editForm.articleTypeId"
              clearable
              placeholder="请选择文章类型"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.articleTypeName"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <div style="margin: 20px 0"></div>
            <div clearable>
              <el-input
                type="text"
                placeholder="请输入文章名"
                v-model="editForm.articleName"
                maxlength="10"
                show-word-limit
              ></el-input>
              <div style="margin: 20px 0"></div>
              <el-input
                type="text"
                placeholder="请输入标题"
                v-model="editForm.articleTitle"
                maxlength="10"
                show-word-limit
              >
              </el-input>
              <div style="margin: 20px 0"></div>
              <el-input
                type="textarea"
                placeholder="请输入简介"
                v-model="editForm.articleAbstract"
                maxlength="30"
                show-word-limit
              >
              </el-input>
              <div style="margin: 20px 0"></div>
              <div id="editor">
                <mavon-editor
                  style="height: 100%; width: 100%"
                  v-model="editForm.articleContent"
                  :ishljs="true"
                  ref="md"
                  @imgAdd="imgAdd"
                  @imgDel="imgDel"
                ></mavon-editor>
              </div>
              <div style="margin: 10px 0"></div>
            </div>
          </el-form>
        </el-form>
      </span>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogvisible = false">取 消</el-button>
        <el-button type="primary" @click="EditSave()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
// import { addPicture } from '../../Api/user'
export default {
  mounted () {
    // 获取文章类型
    this.getArticleType()
    // 获取文章列表
    this.getAllArticle(this.pager)
  },
  data () {
    return {
      // 要操作的行
      currentIndex: 0,
      // 文章列表
      articlelist: [],
      // 分页用到的数据
      pager: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      // 文章类型数组
      options: [],
      // 添加文章表单数据
      addForm: {
        // 类型id
        articleTypeId: '',
        // 文章内容
        articleContent: '',
        // 文章标题
        articleTitle: '',
        // 文章简介
        articleAbstract: '',
        // 文章名
        articleName: ''
      },
      // 编辑文章获取到的表单数据
      editForm: {
        // 类型id
        articleTypeId: '',
        // 文章内容
        articleContent: '',
        // 文章名
        articleName: '',
        // 文章标题
        articleTitle: '',
        // 文章简介
        articleAbstract: ''
      },
      // 控制添加文章对话框的显示和隐藏，默认为false
      addDialogvisible: false,
      // 控制编辑文章对话框的显示和隐藏，默认为false
      editDialogvisible: false,
      selectMsg: {
        msg: ''
      },
      picForm: {
        picPath: ''
      },
      img_file: []
    }
  },
  created () {

  },
  components: {
    mavonEditor
  },
  methods: {
    // 用户名查找用户
    handSelect () {
      if (this.selectMsg.msg) {
        this.SelectArticle(this.selectMsg)
      } else {
        this.getAllArticle(this.pager)
      }
    },
    // 发布文章
    pushArticle () {
      this.addDialogvisible = false
      this.allAddForm = this.addForm
      this.allAddForm.AdminId = parseInt(window.sessionStorage.getItem('id'))
      this.allAddForm.articlesPictureId = 1
      this.allAddForm.isActived = true
      this.AddArticle(this.allAddForm)
    },
    // 保存草稿
    savedraft () {
      this.addDialogvisible = false
      this.allAddForm = this.addForm
      this.allAddForm.AdminId = parseInt(window.sessionStorage.getItem('id'))
      this.allAddForm.articlesPictureId = 1
      this.allAddForm.isActived = false
      this.AddArticle(this.allAddForm)
    },
    // 监听添加文章对话框关闭的事件
    addDialogclosed () {
      this.addForm = {}
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑文章对话框关闭的事件
    editDialogclosed () {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    // 获取文章类型
    async getArticleType () {
      const { data: res } = await this.$http.get('articleType/article')
      console.log(res.data)
      this.options = res.data
    },
    // 获取文章列表
    async getAllArticle (params) {
      console.log(params)
      const { data: res } = await this.$http.get('article/articlesbacken', { params: params })
      console.log(res)
      this.articlelist = res.data
      this.pager.total = res.count
    },
    // 监听 switch 开关状态变化的事件
    async ArticleStatechanged (row) {
      console.log(row)
      const { data: res } = await this.$http.put('article/statu/', row)
      console.log(res)
      if (res.code !== 1000) {
        row.isActived = !row.isActived
        return this.$message.error('更新文章状态失败！')
      }
      return this.$message.success('更新文章状态成功！')
    },
    // 添加文章
    async AddArticle (data) {
      const { data: res } = await this.$http.post('article/addArticle', data)
      this.articlelist.push(res.data)
      console.log(this.articlelist)
      this.getAllArticle(this.pager)
    },
    // 文章名查询
    async SelectArticle (params) {
      params.currentPage = this.pager.currentPage
      params.pageSize = this.pager.pageSize
      params.total = this.pager.total
      const { data: res } = await this.$http.get('Article/articleName', { params: params })
      console.log(res)
      if (res.data) {
        this.articlelist = res.data
        this.pager.total = res.count
      }
    },
    // 删除文章
    async DeleteArticle (id) {
      // 弹框询问用户是否确认删除文章
      const confirmResult = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 取消
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      await this.$http.delete(`article/${id}`)
      this.getAllArticle(this.pager)
    },
    // 修改文章
    async showEidtDialog (index, row) {
      this.editDialogvisible = true
      this.editForm = row
    },
    handleSizeChange (newSize) {
      // pagesize改变触发
      this.pager.pageSize = newSize
      this.getAllArticle(this.pager)
    },
    handleCurrentChange (newPage) {
      // 页码改变触发
      this.pager.currentPage = newPage
      this.getAllArticle(this.pager)
    },
    // 保存文章修改内容
    async EditSave () {
      this.editDialogvisible = false
      await this.$http.put(`article/${this.editForm.id}`, this.editForm)
    },
    // 清空搜索框重新获取数据
    selectArticleList () {
      this.getAllArticle(this.pager)
    },
    // 删除图片
    async imgDel (pos) {
      console.log(pos)
      delete this.img_file[pos]
      const str = pos[0]
      this.picForm.picPath = '/' + str.split('/')[3] + '/' + str.split('/')[4]
      const { data: res } = await this.$http.put('/article/deletepic', this.picForm)
      console.log(res)
      // deletePicture(this.picForm).then((data) => {
      //   console.log(data);
      // });
    },
    // 将图片上传到服务器，返回地址替换到md中
    // 绑定@imgAdd event
    async imgAdd (pos, $file) {
      // 第一步.将图片上传到服务器.
      console.log(pos)
      console.log($file)
      var formdata = new FormData()
      formdata.append('images', $file)
      const { data: res } = await this.$http.post('/article/addpic', formdata, { 'Content-Type': ' multipart/form-data' })
      var url = 'https://cms.zt118.top/' + res.data
      this.$refs.md.$img2Url(pos, url)
    }
  }
}
</script>

<style scoped>
</style>
